<template>
  <div>
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="$parent.open" width="70%" append-to-body>
      <div class="center_dialog">
        <el-divider content-position="center">基本信息</el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="90px" :inline="true">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="循环类型" prop="cycleType">
            <el-select v-model="form.cycleType" placeholder="请选择单位" style="width:100%">
              <el-option v-for="(dict, index) in ['循环巡检', '单次巡检']" :key="index" :label="dict" :value="index + ''">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生成任务" prop="generateTaskType">
            <el-select v-model="form.generateTaskType" placeholder="请选择单位" style="width:100%">
              <el-option v-for="(dict, index) in ['提前一日','提前二日','提前三日','提前四日','提前五日']" :key="index" :label="dict"
                :value="index + ''"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
          <!-- <el-form-item label="内容">
              <editor v-model="form.noticeContent" :min-height="192"/>
            </el-form-item> -->
          <el-divider content-position="center">巡检信息</el-divider>
          <el-button type="primary" plain icon="el-icon-plus" size="medium" @click="handleAddarea">添加巡检区域</el-button>
          <el-form-item label="循环周期" prop="cycle" style="float:right" v-if="form.cycleType === '0'">
            <el-input-number controls-position="right" v-model="form.cycle" placeholder="请输入循环周期">
            </el-input-number>
          </el-form-item>
          <el-form-item label="循环起算日" label-width="95px" prop="specifyTime" style="float:right">
            <el-date-picker v-model="form.specifyTime" type="date" style="width:217px" value-format="yyyy-MM-dd"
              placeholder="请选择循环起算日" />
          </el-form-item>
          <el-table v-loading="loading" :data="noticeList">
            <el-table-column label="序号" align="center" prop="order" width="50" />
            <el-table-column label="巡检员" align="center" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.userName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="所属部门" align="center" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.deptName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="巡检设备数" align="center" min-width="120">
              <template slot-scope="scope">
                <el-link @click="handledetailed(scope.row)" type="primary">{{ scope.row.equipmentCountList || '0' }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column label="巡检时间" align="center" min-width="160">
              <template slot-scope="scope">
                {{ scope.row.inspectionTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="180" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button size="small" type="primary" icon="el-icon-edit"
                  @click="handleUpdate(scope.row,scope.$index)">编辑
                </el-button>
                <el-button icon="el-icon-delete" size="small" type="danger" @click="handleChildrenDelete(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-divider content-position="center">设置循环条件</el-divider>
          <el-form-item label="执行日期" prop="cycleCondition">
            <el-radio-group v-model="form.cycleCondition">
              <el-radio :label="'0'">忽略周末和假期</el-radio>
              <el-radio :label="'1'">遇周末和假期延后执行</el-radio>
              <el-radio :label="'2'">遇周末延后执行</el-radio>
              <el-radio :label="'3'">遇假期延后执行</el-radio>
              <el-radio :label="'4'">遇周末和假期提前执行</el-radio>
              <el-radio :label="'5'">遇周末提前执行</el-radio>
              <el-radio :label="'6'">遇假期提前执行</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div align="center" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="() => $parent.open = false">取 消</el-button>
      </div>

    </el-dialog>
    <template v-if="openArea">
      <AreaChildren :title="titleArea" :index="Areaindex" :AreaObj="AreaObj" @Commit="ChildrenCommit"></AreaChildren>
    </template>
    <template v-if="openSelect">
      <Select :selection="selection"></Select>
    </template>
  </div>
</template>

<script>
import { postCreatelanstatus } from '@/api/equipmentInspct/index.js'
import Upload from '@/components/upload/index.vue'
export default {
  props: ['title', 'rowObj'],
  components: {
    Upload,
    AreaChildren: () => import('./ChildrenValue/area.vue'),
    Select: () => import('./ChildrenValue/Select.vue')
  },
  data () {
    return {
      form: {
        "title": "",     //标题
        "cycleType": "0",    //循环类型（0循环保养 1指定日期）
        "generateTaskType": "", //生成任务（0提前一日 1提前二日 2提前三日 3提前四日 4提前五日）
        "specifyTime": "", //指定日期
        "cycle": undefined,        //循环周期（天）
        "cycleCondition": "",   //循环条件（0忽略周末和假期 1遇周末和假期延后执行 2遇周末延后执行 3遇假期延后执行 4遇周末和假期提前执行 5遇周末提前执行 6遇假期提前执行）
        "remark": "",
        inspectionPlanDetailVos: []
      },
      loading: false,
      inspectorId: '',
      selection: {},
      inspectionTime: '',
      Areaindex: undefined,
      openSelect: false,
      openArea: false,
      AreaObj: {},
      titleArea: '',
      noticeList: [],
      rules: {
        title: { required: true, message: '必填', trigger: 'blur' },
        cycleType: { required: true, message: '必填', trigger: 'blur' },
        generateTaskType: { required: true, message: '必填', trigger: 'blur' },
        specifyTime: { required: false, message: '必填', trigger: 'blur' },
        cycle: { required: true, message: '必填', trigger: 'blur' },
        cycleCondition: { required: true, message: '必填', trigger: 'blur' },
      }
    }
  },
  created () {
    this.getlist()
  },
  methods: {
    /**添加巡检区域 */
    handleAddarea () {
      this.openArea = true
      this.titleArea = '添加巡检区域'
    },
    handleSuccess (res) {
      console.log(res);
      this.form.image = res.res.data.url
    },
    async getlist () {

    },
    // SelectChange () {

    // },
    //提交
    handleChildrenDelete (index) {
      this.noticeList.splice(index, 1)
    },
    handledetailed (row) {
      this.selection = row
      this.openSelect = true
    },
    ChildrenCommit (val) {

      // val.selection.map(item => {
      if (val.index !== undefined) {//修改
        this.noticeList.splice(val.index, 1, {
          selection: val.selection,
          inspectionTime: val.inspectionTime,
          userName: val.userArr.join(','),
          deptName: val.deptArr.join(','),
          inspectorId: val.inspectorId,
          equipmentCountList: val.selection.reduce((pre, cur) => {
            return pre + cur.equipmentCount
          }, 0)
        })
        console.log('修改');
      } else {
        this.noticeList.push(
          {
            selection: val.selection,
            inspectionTime: val.inspectionTime,
            userName: val.userArr.join(','),
            deptName: val.deptArr.join(','),
            inspectorId: val.inspectorId,
            equipmentCountList: val.selection.reduce((pre, cur) => {
              return pre + cur.equipmentCount
            }, 0)
          }
        )
        console.log('新增');

      }
      console.log(val.index);

      // })
      //表格数据去重
      // this.noticeList = this.removedup(this.noticeList, 'areaId')
    },
    submitForm () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let params = {
            ...this.form,
            inspectionPlanDetailVos: this.noticeList.map(item => {
              return {
                inspectionTime: item.inspectionTime,//巡检时间
                inspectionInspectors: item.inspectorId.map(item => { return { inspectorId: item } }),//巡检计划详细关联巡检员对象集合
                inspectionAreas: item.selection.map(item => { return { areaId: item.areaId } })//巡检计划详细关联区域对象集合
              }
            })
          }
          postCreatelanstatus(params).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.$parent.open = false
              this.$parent.handleUpdate()
            }
          })
        }
      });
    },
    handleremoveflie () {
      // 附件删除时调用
      this.form.file = ''
      // for (const key in this.flie) {
      //   this.flie[key] = ''
      // }
    },
    //编辑区域
    handleUpdate (row, index) {
      this.AreaObj = row
      this.Areaindex = index
      this.openArea = true
      this.titleArea = '修改巡检区域'
    },
    beforeAvatarUploadflie (file) {
      // 附件
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['pdf', 'docx', 'doc', 'xlsx', 'xls', 'jpg', 'png']
      const isLt2M = file.size / 1024 / 1024 < 50
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message({
          message: '上传附件支持xls,xlsx ,docx ,doc,pdf,jpg,png格式,大小不超过50M。',
          type: 'warning'
        })
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 50MB!')
        return false
      }
    },
    handlePictureCardflie (file) {
      // 附件成功
      // if (this.form.file !== '') {
      //   return this.$message.error('只可上传一份附件')
      // }
      console.log(file);
      this.form.file = file.data.url
    },
  }
}
</script>

<style lang="scss" scoped>
.center_dialog {
  // text-align: center;
  width: 95%;
  margin: 0px auto;
}
</style>